"""
This is a utility for generating amchart data xml fragments.

generate a container with tag and contents

Look for environment entries starting PREFIX+"."
add suffix and value as tags.
"""

from whiff.middleware import misc
from whiff.rdjson import jsonParse

class xmlContainer(misc.utility):
    def __init__(self, tag, content, prefix=""):
        self.tag = tag
        self.content = content
        self.prefix = prefix
    def __call__(self, env, start_response):
        tag  = self.param_value(self.tag, env)
        prefix  = self.param_value(self.prefix, env)
        content  = self.param_value(self.content, env)
        attributes = {}
        attprefix = prefix+"."
        pl = len(attprefix)
        for (ename, eval) in env.items():
            if ename.startswith(attprefix):
                suffix = ename[pl:]
                attributes[suffix] = eval
        av = attributes.items()
        av.sort()
        avL = []
        for (a,v) in av:
            try:
                v = str(v)
            except UnicodeEncodeError:
                v = unicode(v, errors="ignore")
            jv = jsonParse.format(v)
            avL.append( '\n  %s=%s' % (a, jv))
        atts = "".join(avL)
        fragment = "<%s%s>\n %s\n</%s>" % (tag, atts, content, tag)
        return self.deliver_page(fragment, env, start_response)

__middleware__ = xmlContainer

def test():
    env = {
        "amchart.series.xid": 99,
        "ignorethis": "whatever",
        "amchart.series.event_color": "660077",
        }
    app = xmlContainer("series", "SERIES CONTENT", "amchart.series")
    resp = app(env, misc.ignore)
    txt = "".join(resp)
    print "test text output"
    print txt

if __name__=="__main__":
    test()
